<?php

namespace app\store\controller;
use think\Db;
// 同步节点表
class Tongbu extends Controller
{
    public function syncAccessTree($rootId = 10035)
    {
        // 1. 源数据库连接信息（jbcm_shop）
        $sourceDb = [
            'type'     => 'mysql',
            'hostname' => '127.0.0.1',
            'database' => 'jbcm_shop',
            'username' => 'root',
            'password' => 'f52387d4a852aacc',
            'hostport' => '3306',
            'charset'  => 'utf8',
            'prefix'   => 'yoshop_',
        ];

        // 2. 目标数据库连接信息（yygh_120gcw_com）
        $targetDb = [
            'type'     => 'mysql',
            'hostname' => '127.0.0.1',
            'database' => 'yygh_120gcw_com',
            'username' => 'root',
            'password' => 'f52387d4a852aacc',
            'hostport' => '3306',
            'charset'  => 'utf8',
            'prefix'   => 'yoshop_',
        ];

        // 3. 获取源库中层级数据（4级）
        $sourceData = Db::connect($sourceDb)->query("
            SELECT * FROM yoshop_store_access WHERE access_id = {$rootId}
            UNION
            SELECT * FROM yoshop_store_access WHERE parent_id = {$rootId}
            UNION
            SELECT * FROM yoshop_store_access WHERE parent_id IN (
                SELECT access_id FROM yoshop_store_access WHERE parent_id = {$rootId}
            )
            UNION
            SELECT * FROM yoshop_store_access WHERE parent_id IN (
                SELECT access_id FROM yoshop_store_access WHERE parent_id IN (
                    SELECT access_id FROM yoshop_store_access WHERE parent_id = {$rootId}
                )
            )
        ");
        if (empty($sourceData)) {
            return '没有找到需要同步的数据';
        }

        // 4. 构建 ID 映射并插入目标库（先 parent_id = 0）
        $idMap = [];
        foreach ($sourceData as $item) {
            $newId = Db::connect($targetDb)->table('yoshop_store_access')->insertGetId([
                'name'        => $item['name'],
                'url'         => $item['url'],
                'parent_id'   => 0, // 暂不设置，稍后再更新
                'sort'        => $item['sort'],
                'create_time' => $item['create_time'],
                'update_time' => $item['update_time'],
            ]);
            $idMap[$item['access_id']] = $newId;
        }

        // 5. 回写正确的 parent_id
        foreach ($sourceData as $item) {
            $oldId = $item['access_id'];
            $oldParentId = $item['parent_id'];
            $newId = $idMap[$oldId];
            $newParentId = isset($idMap[$oldParentId]) ? $idMap[$oldParentId] : 0;

            Db::connect($targetDb)->table('yoshop_store_access')
                ->where('access_id', $newId)
                ->update(['parent_id' => $newParentId]);
        }

        return '同步完成，共插入 ' . count($sourceData) . ' 条记录';
    }
}